package com.zxjbyte.yiyi.framework.common.core.okhttp.callback;

import com.zxjbyte.yiyi.framework.common.core.okhttp.IResponseProcessor;
import com.zxjbyte.yiyi.framework.common.core.okhttp.OkResponse;
import com.zxjbyte.yiyi.framework.common.exception.ServiceException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.IOException;
import java.util.function.Consumer;

/**
 * 回调基类
 *
 * @Author zhangxingjia
 * @Date 2024/4/28 13:59
 * @Version: 1.0
 */
@ParametersAreNonnullByDefault
public abstract class AbstractAsyncCallback implements Callback {

    protected final static Consumer<IResponseProcessor> DEFAULT_SUCCESS_CONSUMER = (r) -> {};
    protected final static Consumer<FailureContext> DEFAULT_FAIL_CONSUMER = (r) -> {};

    @Override
    public void onFailure(Call call, IOException e) {
        asFailure(FailureContext.of(call, e));
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        try (OkResponse okResponse = new OkResponse(response)) {
            if (response.isSuccessful()) {
                asSuccess(okResponse);
            } else {
                asFailure(FailureContext.of(call, new ServiceException(response.message()), response.code(), response.headers().toMultimap()));
            }
        } catch (Exception e) {
            asFailure(FailureContext.of(call, e, response.code(), response.headers().toMultimap()));
        }
    }


    /**
     * 失败回调
     * @param context 失败上下文
     */
    protected abstract void asFailure(@Nullable FailureContext context);


    /**
     * 成功回调
     * @param processor
     */
    protected abstract void asSuccess(@Nullable IResponseProcessor processor);

    /**
     * 获取进度回调接口
     *
     * @return
     */
    public IProgressCallback getProgressCallback(){
        return null;
    }

}
